package main

import (
	"log"
	"os"
	"restaurant-system/config"
	"restaurant-system/internal/models"
	"restaurant-system/routes"

	"github.com/gin-gonic/gin"
)

func main() {
	// 初始化数据库
	config.InitDB()

	// 执行数据库迁移
	models.AutoMigrate()

	// 确保上传目录存在
	if err := os.MkdirAll("uploads", 0755); err != nil {
		log.Fatalf("Failed to create upload directory: %v", err)
	}

	// 创建 Gin 实例
	r := gin.Default()

	// 配置跨域
	r.Use(func(c *gin.Context) {
		c.Writer.Header().Set("Access-Control-Allow-Origin", "http://localhost:5173")
		c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
		c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
		c.Writer.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")

		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}

		c.Next()
	})

	// 初始化路由
	routes.InitRoutes(r)

	// 启动服务器
	r.Run(":8080")
}
